//
//  AppDelegate.m
//  rrbi
//
//  Created by kyjun on 16/4/26.
//
//

#import "AppDelegate.h"
#import "MainTabBarViewController.h"

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <IQKeyboardManager/IQToolbar.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AdSupport/AdSupport.h>
#import <AVFoundation/AVFoundation.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>
{
    NSTimer* _timer;
    BOOL _isSys;
}
@property(nonatomic,strong) MainTabBarViewController* mainVC;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //背景颜色
    self.window.backgroundColor = [UIColor whiteColor];
    self.mainVC = [[MainTabBarViewController alloc]init];
    self.window.rootViewController =self.mainVC;
    [self.window makeKeyAndVisible];
    
    
    [self setUpFixiOS11]; //适配IOS 11
    [self startJPush:launchOptions];
    
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
//    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
//    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
//    keyboardManager.enableAutoToolbar = YES; // 控制是否显示键盘上的工具条
//    keyboardManager.shouldShowToolbarPlaceholder = YES; // 是否显示占位文字
//    keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17]; // 设置占位文字的字体
//    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
    return YES;
}
#pragma mark - 适配
- (void)setUpFixiOS11
{
    if (@available(ios 11.0,*)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        UITableView.appearance.estimatedRowHeight = 0;
        UITableView.appearance.estimatedSectionFooterHeight = 0;
        UITableView.appearance.estimatedSectionHeaderHeight = 0;
    }
}

#pragma mark =====================================================  设置极光推送
-(void)startJPush:(NSDictionary*)launchOptions{
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|UNAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {

    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}



- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [JPUSHService setBadge:0];

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //进入前台刷新首页数据通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"FFRONTDeskRefresh" object:nil];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    [JPUSHService setBadge:0];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self handleRemoteNotification:userInfo];
         NSLog(@"2222222 iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

/// 程序运行于前台，后台 或杀死 点击推送通知 都会走这个方法
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self.mainVC jumpHome];
        NSLog(@"333333 iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);

    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertView *test = [[UIAlertView alloc] initWithTitle:title
                                                   message:@"pushSetting"
                                                  delegate:self
                                         cancelButtonTitle:@"yes"
                                         otherButtonTitles:nil, nil];
    [test show];
    
}
#endif


#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
}
#endif



#pragma mark =====================================================  远程通知
/**
 *  接收通知
 *
 *  @param remoteInfo
 */
-(void)handleRemoteNotification:(NSDictionary *)remoteInfo{
    NSLog(@"通知:%@",remoteInfo);
    
        NSDictionary* notificationType = [remoteInfo objectForKey:@"aps"];
        NSString *mp_music = [notificationType objectForKey:@"sound"];
    
    
    if ([mp_music isEqualToString:@"push_new_order.mp3"]) {
        [self PayAudio:mp_music];
    }
    
//        if([mp_music isEqualToString:@"新订单.mp3"]){//订单
//            _isSys = NO;
//            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"] ) {
//                [self PayAudio:mp_music];
//                //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
//            } else {
//            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"]) {//铃声默认
//                [self PayAudio:mp_music];
//            } else {//
//                if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"]) {//震动
//                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
//                }
//            }
//            }
//            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationRemoteAt object:nil];
//        }else if([mp_music isEqualToString:@"push_by_system.mp3"]){//系统
//            _isSys = YES;
//            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"] ) {
//                [self PayAudio:mp_music];
//                //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
//            } else {
//            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"]) {//铃声默认
//                [self PayAudio:mp_music];
//            } else {//
//                if ([[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"]) {//震动
//                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  // 震动
//                }
//            }
//            }
//        }else{
//                //[self PayAudio:mp_music];
//        }
}

static NSInteger t = 0;
-(void)PayAudio:(NSString*)fileName{
    t=0;
    [_timer invalidate];
    self.fileName = fileName;
    _timer = [NSTimer scheduledTimerWithTimeInterval:8.0 target:self selector:@selector(Timered:) userInfo:nil repeats:YES];
}

- (void)Timered:(NSTimer*)timer {
    if (t== 2) {
        [_timer invalidate];
    } else {
        SystemSoundID soundID;
        NSString *path = [[NSBundle mainBundle] pathForResource:self.fileName ofType:nil];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
        
        if (_isSys) {
            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"XITONGXIAOXI_ZHENDONG"] ) {
                AudioServicesPlayAlertSound(soundID);
            } else {
                AudioServicesPlaySystemSound(soundID);
            }
        } else {
            if (![[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_LINGSHENG"] && [[NSUserDefaults standardUserDefaults] boolForKey:@"DINGDANXIAOXI_ZHENDONG"] ) {
                AudioServicesPlayAlertSound(soundID);
            } else {
                AudioServicesPlaySystemSound(soundID);
            }
        }
        AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
            AudioServicesDisposeSystemSoundID(soundID);
            t++;
        });
    }
}

#pragma mark =====================================================  Tabar layout
-(void)layoutTabar{
    NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0],NSFontAttributeName:[UIFont boldSystemFontOfSize:17.f]};
    [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
    [[UINavigationBar appearance] setBackgroundColor:theme_navigation_color];
    [[UINavigationBar appearance] setBarTintColor:theme_navigation_color];
    [[UINavigationBar appearance] setTintColor:theme_default_color];
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    // [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"icon-nav"] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    
    [[UIToolbar appearance] setBackgroundColor:theme_navigation_color];
    [[UIToolbar appearance] setBarTintColor:theme_navigation_color];
    [[UIToolbar appearance] setTintColor:theme_default_color];
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:42/255.0 green:42/255.0 blue:42/255.0 alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:12.f]} forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:30/255.f green:147/255.f blue:238/255.f alpha:1.0],NSFontAttributeName:[UIFont systemFontOfSize:12.f]} forState:UIControlStateSelected];
    
    [[UITableView appearance] setBackgroundColor:theme_table_bg_color];
    [[UICollectionView appearance] setBackgroundColor:theme_table_bg_color];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [[IQToolbar appearance] setBarTintColor:theme_navigation_color];
    [[IQToolbar appearance] setTintColor:theme_default_color];
    
}

@end
